package com.snail.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.snail.common.DeleteRequest;
import com.snail.exception.BusinessException;
import com.snail.exception.ErrorCode;
import com.snail.mapper.*;
import com.snail.model.pojo.*;
import com.snail.model.vo.BizPostPageListVo;
import com.snail.response.BaseResponse;
import com.snail.response.PageResponse;
import com.snail.response.ResultUtils;
import com.snail.service.BizPostService;
import com.snail.service.SysTeamUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Monica
 * @description 针对表【biz_post(帖子表)】的数据库操作Service实现
 * @createDate 2025-07-25 17:03:04
 */
@Service
public class BizPostServiceImpl extends ServiceImpl<BizPostMapper, BizPost>
        implements BizPostService {

    @Autowired
    private BizPostMapper bizPostMapper;
    @Autowired
    private SysTeamMapper sysTeamMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysTagMapper sysTagMapper;
    @Autowired
    private SysTeamUserService sysTeamUserService;
    @Autowired
    private SysTeamUserMapper sysTeamUserMapper;


    @Override
    public PageResponse<BizPost> getAuditedPostPageList(BizPostPageListVo pageListVo) {
        Integer userId = StpUtil.getLoginIdAsInt();
        if (userId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请先登录");
        }
        LambdaQueryWrapper<SysTeamUser> teamUserWrapper = new LambdaQueryWrapper<>();
        teamUserWrapper.eq(SysTeamUser::getUserId, userId);
        teamUserWrapper.eq(SysTeamUser::getTeamId, pageListVo.getTeamId());
        SysTeamUser sysTeamUser = sysTeamUserMapper.selectOne(teamUserWrapper);
        if (sysTeamUser == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请先订阅");
        }

        LambdaQueryWrapper<BizPost> queryWrapper = new LambdaQueryWrapper<>();
        Page<BizPost> bizPostPage = new Page<>(pageListVo.getCurrent(), pageListVo.getPageSize());
        if (StringUtils.hasLength(pageListVo.getTitle())) {
            queryWrapper.like(BizPost::getTitle, pageListVo.getTitle());
        }
        if (StringUtils.hasLength(pageListVo.getTagId())) {
            queryWrapper.like(BizPost::getTagIds, pageListVo.getTagId());
        }
        if (pageListVo.getStartPublishTime() != null) {
            queryWrapper.ge(BizPost::getPublishTime, pageListVo.getStartPublishTime());
        }
        if (pageListVo.getEndPublishTime() != null) {
            queryWrapper.le(BizPost::getPublishTime, pageListVo.getEndPublishTime());
        }
        queryWrapper.orderByDesc(BizPost::getPublishTime);
        queryWrapper.eq(BizPost::getStatus, 1);
        if (pageListVo.getTeamId() != null) {
            queryWrapper.eq(BizPost::getTeamId, pageListVo.getTeamId());
        }
        Page<BizPost> bizPostPageList = bizPostMapper.selectPage(bizPostPage, queryWrapper);
        bizPostPageList.getRecords().forEach(bizPost -> {
            bizPost.setTagIds(analyzeTags(bizPost.getTagIds(), 1));
            SysUser sysUser = sysUserMapper.selectById(bizPost.getUserId());
            bizPost.setUsername(sysUser.getUsername());
            bizPost.setAvatar(sysUser.getFilePath());
        });
        return ResultUtils.pageSuccess(bizPostPageList);
    }

    @Override
    public PageResponse<BizPost> getUnauditedPostPageList(BizPostPageListVo pageListVo) {
        Integer userId = StpUtil.getLoginIdAsInt();
        if (userId == null) {
            return null;
        }

        // 1查询我创建的战队
        LambdaQueryWrapper<SysTeam> teamQuery = new LambdaQueryWrapper<>();
        teamQuery.eq(SysTeam::getCreatorId, userId);
        List<SysTeam> createdTeams = sysTeamMapper.selectList(teamQuery);

        // 2️查询我作为队长管理的战队
        LambdaQueryWrapper<SysTeamUser> captainQuery = new LambdaQueryWrapper<>();
        captainQuery.eq(SysTeamUser::getUserId, userId).eq(SysTeamUser::getRole, 1);
        List<SysTeamUser> captainTeams = sysTeamUserMapper.selectList(captainQuery);

        // 3️合并 teamId 去重
        Set<Long> teamIds = new HashSet<>();
        if (createdTeams != null) {
            teamIds.addAll(createdTeams.stream().map(SysTeam::getId).toList());
        }
        if (captainTeams != null) {
            teamIds.addAll(captainTeams.stream().map(SysTeamUser::getTeamId).toList());
        }

        if (teamIds.isEmpty()) {
            return ResultUtils.pageSuccess(new Page<>()); // 没有可审核的战队，返回空分页
        }

        // 4构建帖子查询条件
        LambdaQueryWrapper<BizPost> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasLength(pageListVo.getTitle())) {
            queryWrapper.like(BizPost::getTitle, pageListVo.getTitle());
        }
        if (StringUtils.hasLength(pageListVo.getTagId())) {
            queryWrapper.like(BizPost::getTagIds, pageListVo.getTagId());
        }
        if (pageListVo.getStartPublishTime() != null) {
            queryWrapper.ge(BizPost::getPublishTime, pageListVo.getStartPublishTime());
        }
        if (pageListVo.getEndPublishTime() != null) {
            queryWrapper.le(BizPost::getPublishTime, pageListVo.getEndPublishTime());
        }

        queryWrapper.eq(BizPost::getStatus, 2); // 未审核
        queryWrapper.in(BizPost::getTeamId, teamIds);
        queryWrapper.orderByDesc(BizPost::getPublishTime);

        // 5️分页查询
        Page<BizPost> bizPostPage = new Page<>(pageListVo.getCurrent(), pageListVo.getPageSize());
        Page<BizPost> bizPostPageList = bizPostMapper.selectPage(bizPostPage, queryWrapper);

        // 6️填充用户信息
        bizPostPageList.getRecords().forEach(bizPost -> {
            bizPost.setTagIds(analyzeTags(bizPost.getTagIds(), 1));
            SysUser sysUser = sysUserMapper.selectById(bizPost.getUserId());
            if (sysUser != null) {
                bizPost.setUsername(sysUser.getUsername());
                bizPost.setAvatar(sysUser.getFilePath());
            }
        });

        return ResultUtils.pageSuccess(bizPostPageList);
    }

    @Override
    public BaseResponse delete(DeleteRequest request) {
        bizPostMapper.deleteById(request.getId());
        return ResultUtils.success();
    }

    @Override
    public BaseResponse edit(BizPost bizPost) {
        bizPostMapper.updateById(bizPost);
        return ResultUtils.success();
    }

    @Override
    public BaseResponse publish(BizPost bizPost) {
        bizPost.setStatus(1);
        bizPostMapper.insert(bizPost);
        return ResultUtils.success();
    }

    public String analyzeTags(String tagsIds, Integer types) {
        if (tagsIds == null || tagsIds.trim().isEmpty()) {
            return "";
        }
        try {
            List<Integer> tagIdList = Arrays.stream(tagsIds.split(",")).map(String::trim).filter(s -> !s.isEmpty()).map(Integer::valueOf).collect(Collectors.toList());

            if (tagIdList.isEmpty()) {
                return "";
            }
            LambdaQueryWrapper<SysTag> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(SysTag::getId, tagIdList).eq(SysTag::getTagType, types);

            List<SysTag> sysTags = sysTagMapper.selectList(queryWrapper);

            return sysTags.stream().map(SysTag::getTagName).filter(Objects::nonNull).collect(Collectors.joining(","));
        } catch (NumberFormatException e) {
            return "";
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean reviewPost(Long teamId, Long userId, Long id, Integer status) {
        // 校验当前用户是不是战队队长
        LambdaQueryWrapper<SysTeamUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysTeamUser::getUserId, userId)
                .eq(SysTeamUser::getTeamId, teamId)
                .eq(SysTeamUser::getRole, 1);
        SysTeamUser captain = sysTeamUserService.getOne(queryWrapper);
        if (captain == null) {
            throw new BusinessException(ErrorCode.FORBIDDEN_ERROR, "您不是该战队的队长,没有权限审核帖子");
        }
        // 校验待审核的帖子是否存在该战队
        LambdaQueryWrapper<BizPost> postStatus = new LambdaQueryWrapper<>();
        postStatus.eq(BizPost::getId, id)
                .eq(BizPost::getTeamId, teamId)
                .eq(BizPost::getStatus, 2);// 帖子待审核

        BizPost bizPost = this.getOne(postStatus);
        if (bizPost == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "待审核的帖子不存在");
        }
        // 审核该帖子
        bizPost.setStatus(status);
        boolean success = this.updateById(bizPost);
        return success;
    }


}




